<?php header('Access-Control-Allow-Origin:*'); ?>
<?php

    error_reporting(-1);
$isin = array(); //Whether visited

function getNode($id, $bufferCh=true)
{
   global $db;
    $result = $db->query("select * from t where id=".$id."  LIMIT 1");
   return $result->fetchArray();
}

    function toINT(&$val, $key)
    {
        $val = (int)($val);
    }
    
function str2list($s)
{
    $l = explode("|",$s);
    array_walk($l, "toINT");
    
    return $l;
}
function addQuote(&$val, $key)
{
    $val;
}
function listWithQuote($l)
{
    return $l;
}

function directQuotedStr($s)
{
    return str_replace("|", ',', $s);
}

function node2str($n, $refLevel=0)
{
    if (!$n) return null;
    //var_dump($n);
    $ss = "";
    $ss = sprintf(' 
    { 
        "id":           %d,
        "name":         \'%s\',
        "edgeFrom":     [%s],
        "edgeTo":       [%s],
        "info":         "%s"
    }
    ', $n["id"], htmlspecialchars($n["name"], ENT_QUOTES), directQuotedStr($n["ref"]), directQuotedStr($n["refed"]),
    str_replace(
                '"','&quot;', ' <h4>Name</h4> '. $n["name"] . '<h4>Author</h4>' . $n["author"]. "<h4>Date</h4>" . $n["date"] . "<h4> Magazine/Conference </h4>" . $n["mag"])
    );
    return $ss;
}


function dfs($id, $level, $rawdep)
{
   
    global $isin;
    global $s;
    global $d;
    global $cur;
    if ($rawdep>$d) return;
    if (array_key_exists($id, $isin)) return;
    $isin[$id] = true;
    
    $nn = getNode($id, ($rawdep<$d));
    
    if ($nn)
    {
        if ($id != $cur) echo ",";
    
        echo node2str($nn, $level);
    }
    $ref = str2list($nn["ref"]);
    
    foreach($ref as $c)
        dfs($c, $level+1, $rawdep+1);
    
    $refed = str2list($nn["refed"]);
    
    foreach($refed as $c)
        dfs($c, $level-1, $rawdep+1);
}

    echo '[';

    $cur = (int)($_GET["id"]);
    $d = (int)($_GET["dep"])-1;
    
    $s = "";
    $t1 = microtime(true);
    
    $db = new SQLite3('test.db');
    
    
    dfs($cur, 0,0);
    
    $t2 = microtime(true);
    
    echo $s . "]";
   echo '//'.round($t2-$t1,3)."second  with ".count($isin)."Nodes";
    
    
?>
